//
//  CTCAnswerConsultVC.m
//  ConsultantVersion
//
//  Created by 李小龙 on 2017/3/27.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "CTCAnswerConsultVC.h"
#import "CTCConsultDetailTableViewController.h"
#import "CTCOfflineConsultQuestionDetailVC.h"

// cell
#import "CTCConsultQuestionCell.h"
#import "CTCOfflineConsultRecordsCell.h"

// view
#import "CTCOfflineSwitchView.h"

// model
#import "CTCOfflineConsultRecordsModel.h"


/*线下咨询cell重用id*/
static NSString *const kOfflineCellReuseID = @"kOfflineCellReuseID";


@interface CTCAnswerConsultVC ()
/** 线上咨询*/
@property (nonatomic, strong) NSMutableArray *questionArr;
/** 线下咨询 */
@property (nonatomic, strong) CTCOfflineConsultRecordsModel *recordsModel;

/** 页码 */
@property (nonatomic, assign) NSInteger onlineLastIndex;

/** 数据源的最后ID */
@property (nonatomic, assign) NSInteger offlineLastIndex;

/** 是否为线上咨询 */
@property (nonatomic, assign) BOOL isOnline;


@end

@implementation CTCAnswerConsultVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavBar];
    [self setupTableView];
    [self setupConfig];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadRedStatus:) name:kReloadO2OListRedBadgeNotification object:nil];
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [[NSNotificationCenter defaultCenter] postNotificationName:kShowO2OConsultRedBadgeNotification object:nil];
    [self.tableView.mj_header beginRefreshing];
    [self getTabBarRedBadgeData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    DeLog(@"个数---%ld",self.questionArr.count);
    
    return _isOnline? self.questionArr.count: self.recordsModel.data.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_isOnline) {
        
        CTCConsultQuestionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CTCConsultQuestionCell" forIndexPath:indexPath];
        cell.questionModel = self.questionArr[indexPath.section];
        // Configure the cell...
        cell.isLimitThree = YES;
        
        return cell;
    }else {
        
        CTCOfflineConsultRecordsDataModel *dataM = self.recordsModel.data[indexPath.section];
        CTCOfflineConsultRecordsCell *cell = [tableView dequeueReusableCellWithIdentifier:kOfflineCellReuseID forIndexPath:indexPath];
        
        cell.dataModel = dataM;
        
        return cell;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (_isOnline) { // 线上咨询
        
        CTCConsultDetailTableViewController  *vc = [[CTCConsultDetailTableViewController alloc]init];
        
        CTCQuestionModel *model = self.questionArr[indexPath.section];
        vc.questionModel = model ;
        
        MPWeakSelf(self);
        vc.answerSuccessBlock = ^(){
            model.status = @"1";
            NSLog(@"调没有 reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil]  ");
            [weakself.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationFade];
            
        };
        
        [self.navigationController pushViewController:vc animated:YES];
    }else { // 线下咨询
        CTCOfflineConsultRecordsDataModel *dataM = self.recordsModel.data[indexPath.section];
        
        CTCOfflineConsultQuestionDetailVC *offlineVC = [[CTCOfflineConsultQuestionDetailVC alloc] initWithQuestionDetailModel:dataM];
        
        [self.navigationController pushViewController:offlineVC animated:YES];
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}


- (void)reloadRedStatus:(NSNotification *)notification
{
//    NSIndexPath *indexPath = self.tableView.indexPathForSelectedRow;
//    CTCQuestionModel *model = self.questionArr[indexPath.section];
//    model.status = @"1";
//    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationFade];
    [self loadNewest];
}


#pragma mark -- 网络请求
- (void)requestOfflineConsultRecords {
    
    [RequestTool POST:kOfflineConsultRecordsURL
           parameters:@{@"pageIndex" : @(_offlineLastIndex), @"pageEnd" : @(_offlineLastIndex + 9)}
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  [self stopRefresh];

                  DeLog(@"线下咨询记录--%@",responseObject);
                  CTCOfflineConsultRecordsModel *recordsModel = [CTCOfflineConsultRecordsModel yy_modelWithJSON:responseObject];
                  if (recordsModel.code.intValue == 1) {
                      
                      _isOnline = NO;
                      if (!self.recordsModel) {
                          
                          self.recordsModel = recordsModel;
                          _offlineLastIndex += recordsModel.data.count;
                          
                      }else {
                          self.recordsModel.data = [self.recordsModel.data arrayByAddingObjectsFromArray:recordsModel.data];
                          _offlineLastIndex += recordsModel.data.count;
                      }
                      [self.tableView reloadData];
                      
                  }else if (recordsModel.code.intValue == 2){
                      [MBProgressHUD showTipMessageInView:@"请登录"];
                      
                      CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                      MPWeakSelf(self);
                      vc.loginSuccess = ^(){
                          [weakself loadNewest];
                      };
                      [self presentViewController:vc animated:YES completion:nil];
                  }else{
                      
                      [MBProgressHUD showErrorMessage:recordsModel.des];
                  }
                  
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  [self stopRefresh];
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
                  
              }
     ];
    
}


- (void)getTabBarRedBadgeData{
    
    [RequestTool POST:kTabBarRedBadgeUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"kTabBarRedStatusURL---responseObject %@", responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            if ([responseObject[@"data"][@"rapidRed"] integerValue]) {
                [self.tabBarController.tabBar.items[0] showBadge];
            } else {
                [self.tabBarController.tabBar.items[0] hidenBadge];
            }
            
            if (([responseObject[@"data"][@"oneRed"]  integerValue]) ||([responseObject[@"data"][@"lineDownRed"]  integerValue])) {
                [self.tabBarController.tabBar.items[1] showBadge];
            } else {
                [self.tabBarController.tabBar.items[1] hidenBadge];
            }
            
        }
        else {
            [MBProgressHUD showInfoMessage:responseObject[@"des"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error %@", error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
}

- (void)requestOnlineConsultRecords
{
    
    NSMutableDictionary *paramsDic = [NSMutableDictionary dictionary];
    paramsDic[@"pageIndex"] = @(self.onlineLastIndex);
    paramsDic[@"pageEnd"] = @(self.onlineLastIndex+9);
    
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kAnswerConsultListUrl
           parameters:paramsDic
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"response %@", responseObject);
                  [self stopRefresh];
                  CTCResponderQuestionListModel *listModel = [CTCResponderQuestionListModel yy_modelWithJSON:responseObject];
                  NSInteger code = [listModel.code integerValue];
                  if (code == 1) {
                      _isOnline = YES;
                      [MBProgressHUD hideHUD];
                      [self.questionArr addObjectsFromArray:listModel.questionArr];
                      self.onlineLastIndex += self.questionArr.count;
                      [self.tableView reloadData];
                      
                  }else {
                      [MBProgressHUD showErrorMessage:listModel.des];
                      
                      if (code == 2) {
                          CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                          MPWeakSelf(self);
                          vc.loginSuccess = ^(){
                              [weakself loadNewest];
                          };
                          [self presentViewController:vc animated:YES completion:nil];
                      }
                  }
                  
              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  DeLog(@"error %@", error);
                  [self stopRefresh];
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
              }];
}

- (void)loadNewest
{
    if (_isOnline) {
        
        self.onlineLastIndex = 1;
        [self.questionArr removeAllObjects];
        [self requestOnlineConsultRecords];
    }else {
        self.offlineLastIndex = 1;
        self.recordsModel = nil;
        [self requestOfflineConsultRecords];
    }
}

- (void)loadMoreHistory {
    if (_isOnline) {
        
        [self requestOnlineConsultRecords];
        
    }else {
        
        [self requestOfflineConsultRecords];
    }
    
}
- (void)stopRefresh
{
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
}


- (void)setupConfig
{
    _isOnline = YES;
    self.onlineLastIndex = 1;
    self.offlineLastIndex     = 1;
    // MARK:注释线下线上咨询切换

//    CTCOfflineSwitchView *switchTitleView = [[CTCOfflineSwitchView alloc] initWithSwitchBlock:[self returnOfflineSwitchBlock]];
//    [switchTitleView.layer setBorderColor:[UIColor whiteColor].CGColor];
//    [switchTitleView.layer setBorderWidth:1];
//    switchTitleView.layer.cornerRadius = 5;
//    switchTitleView.clipsToBounds = YES;
//
//    switchTitleView.frame =  CGRectMake(0, 0, 180, 28);
//    self.navigationItem.titleView = switchTitleView;
}

- (void)setupTableView
{
    self.tableView.estimatedRowHeight = 200;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.sectionHeaderHeight = 10;
    self.tableView.sectionFooterHeight = 0;
    self.tableView.contentInset = UIEdgeInsetsMake(11-35, 0, 0, 0);
    [self.tableView registerClass:[CTCOfflineConsultRecordsCell class] forCellReuseIdentifier:kOfflineCellReuseID];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewest];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreHistory];
    }];
}

#pragma mark -- 私有方法
- (CTCOfflineSwitchViewSwitchBlock)returnOfflineSwitchBlock {
    CTCOfflineSwitchViewSwitchBlock block = nil;
    MJWeakSelf;
    block = ^(NSInteger idx) {
        if (idx==1) { // 线上咨询
            
            weakSelf.onlineLastIndex = 1;
            [weakSelf.questionArr removeAllObjects];
            [weakSelf requestOnlineConsultRecords];
            
        }else { // 线下咨询
            weakSelf.offlineLastIndex = 1;
            weakSelf.recordsModel = nil;
            [weakSelf requestOfflineConsultRecords];
        }
        [weakSelf getTabBarRedBadgeData];
    };
    return block;
}


#pragma mark -- lazyload

- (NSMutableArray *)questionArr
{
    if (!_questionArr) {
        _questionArr = [NSMutableArray array];
    }
    
    return _questionArr;
}

- (void)setupNavBar
{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, App_Frame_Width, 44)];
    label.text = @"咨询记录";
    label.textColor = [UIColor whiteColor];
    label.font = SYSTEMFONT(17);
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = label;
}

@end
